#region License, Terms and Conditions
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
#endregion
using System;
using System.Net;
using System.Web;
using pesta.Data;
using Pesta.Engine.protocol.conversion;
using Pesta.Engine.social.spi;
using pesta.Data.Model.Helpers;

namespace raya.Library
{
    public class GoogleFriendConnect
    {
#if (DEBUG)
        private static readonly string authCookieName = "fcauth" + RayaSettings.Gfc_key + "-s"; 
#else
        private static readonly string authCookieName = "fcauth" + RayaSettings.Gfc_key;
#endif
        private const string baseUrl = "http://www.google.com/friendconnect/api/";

        private string authCookie;
        public Person gfcUser { get; set; } 
        private readonly BeanJsonConverter converter;

        public GoogleFriendConnect()
        {
            converter = new BeanJsonConverter();
        }

        private void GetAuthCookie()
        {
            if (HttpContext.Current.Request.Cookies[authCookieName] != null)
            {
                authCookie = HttpContext.Current.Request.Cookies[authCookieName].Value;
            }
        }

        public Person GetViewerData()
        {
            OpenSocialUrl url = new OpenSocialUrl(baseUrl);
            url.addPathComponent("people/@viewer/@self");
            url.addQueryStringParameter("fcauth", authCookie);

            OpenSocialHttpRequest req = new OpenSocialHttpRequest(url);
            if (req.execute() != HttpStatusCode.OK.ToInt())
            {
                throw new OpenSocialRequestException(req.getResponseString() + ": " + url);
            }
            var jsonString = req.getResponseString();
            if ((jsonString.IndexOf('[') != -1) && jsonString.IndexOf('[') < jsonString.IndexOf('{'))
            {
                throw new NotImplementedException();
            }
            else // single entry response
            {
                return converter.ConvertToObject<RestfulEntry<Person>>(jsonString).entry;
            }
        }

        public bool isConnected()
        {
            GetAuthCookie();
            if (string.IsNullOrEmpty(authCookie))
            {
                return false;
            }
            try
            {
                gfcUser = GetViewerData();
            }
            catch (Exception ex)
            {
                ClearGFCCookies();
                return false;
            }
            return true;
        }

        public static void ClearGFCCookies()
        {
            if (HttpContext.Current != null &&
                HttpContext.Current.Response.Cookies[authCookieName] != null)
            {
                HttpContext.Current.Response.Cookies[authCookieName].Expires = DateTime.Now.AddMonths(-1);
            }
        }
    }
}
